package com.orangesale.cn.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.orangesale.cn.R;
import com.orangesale.cn.entity.OrangeMessage;
import com.orangesale.cn.netrequest.OkHttpMessage;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class TimeService extends Service {
    private static Timer timer = null;
    private NotificationManager manager;
    private NotificationCompat.Builder builder;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 清除通知
     */
    private void cleanAllNotification() {
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancelAll();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }

    }

    /**
     * 添加通知
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        long period = 60 * 1000; //1分钟一个周期
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                new ConsumeMessageTask().execute();
            }
        }, 0, period);

        return super.onStartCommand(intent, flags, startId);
    }

    class ConsumeMessageTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            /**
             * NotificationChannel是android8.0新增的特性，如果App的targetSDKVersion>=26，
             * 没有设置channel通知渠道的话，就会导致通知无法展示。
             * 报错内容：Failed to post notification on channel “null”
             */
            OkHttpMessage okHttpMessage = new OkHttpMessage();
            OrangeMessage orangeMessage;
            try {
                orangeMessage = okHttpMessage.consumeMessage();
                if (!Objects.isNull(orangeMessage)) {
                    Log.i("orangeMessage", "run: " + orangeMessage.toString());
                    NotificationChannel channel = new NotificationChannel("channel", "通知", NotificationManager.IMPORTANCE_DEFAULT);
                    manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                    manager.createNotificationChannel(channel);
                    builder = new NotificationCompat.Builder(TimeService.this);
                    Date date = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    builder.setContentTitle("来自橙一色的系统通知消息" + "  " + formatter.format(date));
                    builder.setSmallIcon(R.drawable.chengzi);
                    builder.setChannelId("channel");
                    builder.setContentText(orangeMessage.getContent());
                    builder.setAutoCancel(true);
                    builder.setDefaults(Notification.DEFAULT_ALL);
                    Notification notification = builder.build();
                    manager.notify(1, notification);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
